package com.example.medical.service.impl;

import com.example.medical.service.EquipmentImageService;
import com.example.medical.domain.EquipmentImage;
import com.example.medical.mapper.EquipmentImageMapper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service
public class EquipmentImageServiceImpl implements EquipmentImageService {

    @Resource
    private EquipmentImageMapper equipmentImageMapper;

    // 实现器械图片上传的业务逻辑，包括保存图片文件到本地（也可根据实际改为存储到云存储等）及插入器械图片数据到数据库
    @Override
    public boolean uploadEquipmentImage(EquipmentImage equipmentImage, MultipartFile imageFile) {
        if (!imageFile.isEmpty()) {
            try {
                // 定义图片存储的本地路径，可根据实际需求调整
                String filePath = "D:\\medical\\equipment_images";
                // 获取原始文件名
                String originalFileName = imageFile.getOriginalFilename();
                // 生成新的文件名，防止文件名冲突，这里使用UUID
                String newFileName = UUID.randomUUID().toString() + "." + originalFileName.substring(originalFileName.lastIndexOf('.') + 1);
                // 构建完整的文件保存路径
                File dest = new File(filePath + newFileName);
                // 将文件保存到本地磁盘
                imageFile.transferTo(dest);
                // 设置器械图片对象中的图片地址为保存后的路径
                equipmentImage.setImageUrl(filePath + newFileName);
                // 调用Mapper层方法插入器械图片数据到数据库
                int result = equipmentImageMapper.insertEquipmentImage(equipmentImage);
                return result > 0;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }
    @Override
    public List<EquipmentImage> getAllImages() {
        return equipmentImageMapper.getAllImages();
    }
    // 实现删除器械图片的业务逻辑，调用Mapper层方法根据ID删除器械图片数据
    @Override
    public boolean deleteEquipmentImage(int id) {
        int result = equipmentImageMapper.deleteEquipmentImageById(id);
        return result > 0;
    }

    @Override
    public List<EquipmentImage> getImagesByEquipmentName(String equipmentName) {
        return equipmentImageMapper.selectImagesByEquipmentName(equipmentName);
    }
    // 实现更新器械图片信息的业务逻辑，调用Mapper层方法根据传入的器械图片对象更新数据库中对应记录
    @Override
    public boolean updateEquipmentImage(EquipmentImage equipmentImage) {
        int result = equipmentImageMapper.updateEquipmentImageById(equipmentImage);
        return result > 0;
    }
}